<template>
  <view>
    <Search @openGpt="getCategoryData" />
    <view class="order-menu">
      <scroll-view class="scroll-height-left" scroll-y enhanced enable-passive :show-scrollbar="false">
        <view class="left-goods" :class="{ activeStyle: index == currentIndex }" v-for="(item, index) in goodsList"
          :key="item._id" @tap="handleAnchor(index, item._id)">
          <image :src="item.icon" mode="widthFix" />
          <text>{{ item.categoryName }}</text>
        </view>
      </scroll-view>
      <scroll-view :scroll-into-view="currentId" class="scroll-height-right" scroll-y enhanced enable-passive
        :show-scrollbar="false" @scroll="handleRightScroll">
        <view class="item-goods" :id="'A' + item._id" v-for="(item, index) in goodsList" :key="item._id">
          <text class="category-title">{{ item.categoryName }}</text>
          <view class="goods-infor" :id="'B' + goods._id" v-for="(goods, goods_index) in item.goodsList" :key="goods._id"
            @tap="goDetail(goods._id)">
            <image :src="goods.image" mode="aspectFill" />
            <view class="product-name">
              <text class="googs-name">{{ goods.name }}</text>
              <text class="googs-intro overflow-text">
                {{ goods.description }}
              </text>
              <view class="select-goods">
                <view class="goods-price">
                  <text>￥{{ goods.price }}</text>
                  <text>起</text>
                </view>
                <block v-if="goods.stock > 0">
                  <view class="select-quantity" v-if="goods.attribute?.length">
                    <button>选规格</button>
                    <text v-if="goods.quantity">{{ goods.quantity }}</text>
                  </view>
                  <view class="select-goods single-goods" v-else>
                    <image src="/static/jian-goods.png" mode="widthFix" v-if="goods.quantity"
                      @tap.stop="handleProduct(index, goods_index, -1)" />
                    <text v-if="goods.quantity">{{ goods.quantity }}</text>
                    <image src="/static/jia-goods.png" mode="widthFix" @tap.stop="handleProduct(index, goods_index, 1)" />
                  </view>
                </block>
                <view v-else><button disabled>已售罄</button></view>
              </view>
            </view>
          </view>
        </view>
        <view style="height: 400rpx"></view>
      </scroll-view>
    </view>
    <Cart />
  </view>
</template>
<script setup lang="ts">
import { ref, watch } from "vue";
import Search from "./components/Search.vue";
import Cart from "./components/Cart.vue";
import request from "@/api/request";
import type { CategoryInfo } from "@/types";
import Decimal from "decimal.js";
import { useStore } from "@/store";
const goodsList = ref<CategoryInfo[]>([]);
const currentIndex = ref(0);
const currentId = ref();
const itemHeight = ref<number[]>([]);
const store = useStore();

const getCategoryData = async () => {
  const { data } = await request<CategoryInfo[]>("/getCategoryGoods");
  goodsList.value = data;
  setTimeout(() => {
    calculateGoodsHeight();
  }, 500);
  console.log(data);
};
const goDetail = (_id: string) => {
  uni.navigateTo({ url: "/pages/productDetail/index?_id=" + _id });
};
const handleAnchor = (index: number, id: string) => {
  currentIndex.value = index;
  currentId.value = "A" + id;
  // setTimeout(() => {
  //   currentId.value = ""; //避免在当前列表下点击不能滚动到顶部
  // });
};
// 计算右边有个分类下的高度
const calculateGoodsHeight = () => {
  // 获取元素节点信息
  const query: any = uni.createSelectorQuery();
  query
    .selectAll(".item-goods")
    .boundingClientRect()
    .exec((res: { height: number; }[][]) => {
      const heights = res[0].map((item) => item.height);
      const reduceHeight: number[] = [];
      heights.reduce((a, b) => {
        reduceHeight.push(a + b);
        return a + b;
      }, 0);
      itemHeight.value = reduceHeight;
    });
};
const handleRightScroll = (event: { detail: { scrollTop: number; }; }) => {
  const findIndex = itemHeight.value.findIndex(
    (index) => index > event.detail.scrollTop
  );
  currentIndex.value = findIndex;
};
const handleProduct = (categoryIndex: number, goodsIndex: number, num: -1 | 1) => {
  const goods = goodsList.value[categoryIndex].goodsList[goodsIndex];
  goods.quantity += num;
  const params = {
    categoryId: goods!.categoryId,
    goodsId: goods!._id,
    name: goods!.name,
    image: goods!.image,
    price: goods.price,
    specs: [],
    sid: [],
    quantity: num,
    attrId: "",
    totalPrice: Decimal(goods.price).times(new Decimal(goods!.quantity)),
  };
  store.addTocart(params);
  console.log("cxcxc", params, Number(params.totalPrice));

  console.log(store.cartItems);
};
// 监听购物车每一个商品数量的变化，从而根据下标找到当前页面商品并更新
watch(() => store.cartItems.map(item => item.quantity), (newValue, oldValue) => {
  // [2,1],[3,1]
  if (newValue.length) {
    for (let i = 0; i < newValue.length; i++) {
      if (newValue[i] != oldValue[i]) {
        const goodsItem = store.cartItems[i];
        const findItem = goodsList.value.find(item => item._id === goodsItem.categoryId)?.goodsList.find(item => item._id === goodsItem.goodsId);
        // 有规格商品，购物车查找相同goods_id的商品做数量累加
        if (findItem?.attribute.length) {
          const totalQuantity = store.cartItems.filter(item => item.goodsId === findItem._id).reduce((a, b) => a + b.quantity, 0);
          findItem.quantity = totalQuantity;
        } else {
          findItem!.quantity = newValue[i];
        }
        return;
      }
    }

  } else {
    if (goodsList.value.length) {
      goodsList.value.forEach(item => item.goodsList.forEach(item2 => item2.quantity = 0));
    }
  }
});
watch(() => [store.swiperParams, goodsList.value.length], ([swiperParams, goodsLength]: any) => {
  if (goodsLength && Object.keys(swiperParams).length) {
    const categoryIndex = goodsList.value.findIndex(item => item._id == swiperParams.categoryId);

    const goodsItem = goodsList.value[categoryIndex].goodsList.find(item => item._id == swiperParams.goodsId);
    currentId.value = "B" + goodsItem!._id;
    currentIndex.value = categoryIndex;

    setTimeout(() => {
      currentId.value = ""; //避免在当前列表下点击不能滚动到顶部
    });
  }

});
// 
</script>
<style>
.order-menu {
  display: flex;
}

/* 左边商品分类滚动 */
.scroll-height-left {
  height: 100vh;
  width: 175rpx;
  background-color: #f8f8f8;
  position: fixed;
  left: 0;
}

.left-goods {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 25rpx;
  padding: 15rpx 0;
}

.left-goods image {
  width: 65rpx;
}

.left-goods title {
  padding-top: 10rpx;
  color: #777777;
}

.activeStyle {
  background-color: antiquewhite;
}

/* 右边商品 */
.scroll-height-right {
  flex: 1;
  padding: 0 20rpx;
  height: 100vh;
  position: fixed;
  right: 0;
  left: 175rpx;
  width: auto;
}

.item-goods {
  padding-top: 35rpx;
}

.category-title {
  font-weight: bold;
}

.goods-infor {
  display: flex;
  align-items: center;
  padding-top: 35rpx;
}

.goods-infor image {
  width: 170rpx;
  height: 170rpx;
  border-radius: 15rpx;
}

.product-name {
  flex: 1;
  padding-left: 15rpx;
}

.googs-name {
  font-weight: bold;
  font-size: 29rpx;
}

.googs-intro {
  line-height: 1.4;
  color: #b8b8b8;
  font-size: 25rpx;
  margin: 13rpx 0;
}

.select-goods {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.goods-price {
  display: flex;
  flex: 1;
}

.goods-price text:nth-child(1) {
  font-size: 30rpx;
  font-weight: bold;
  padding-right: 10rpx;
}

.goods-price text:nth-child(2) {
  font-size: 24rpx;
  color: #b8b8b8;
  align-self: flex-end;
}

.select-quantity {
  position: relative;
}

.select-quantity button {
  font-size: 28rpx;
  line-height: inherit;
  background-color: #214bd5;
  color: #ffffff;
  padding: 5rpx 20rpx;
  border-radius: 40rpx;
}

.select-quantity text {
  position: absolute;
  top: -7rpx;
  right: 0;
  background: bisque;
  border-radius: 50%;
  width: 30rpx;
  height: 30rpx;
  font-size: 18rpx;
  text-align: center;
  line-height: 30rpx;
}

.single-goods image {
  width: 45rpx;
  height: 45rpx;
}

.single-goods text {
  font-size: 26rpx;
  width: 63rpx;
  text-align: center;
}
</style>
